import json
from pathlib import Path
import logging
import queue

from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import QWidget

CFG_FILE_NAME = 'Excel_merge_config.json'
my_logger = logging.getLogger('LogHelper')
my_logger.setLevel(logging.DEBUG)


class Signal:
    MIN_WINDOW_SIGNAL = 0
    MAX_WINDOW_SIGNAL = 1
    CLOSE_WINDOW_SIGNAL = 2


class Config:
    def __init__(self):
        self.GLOBAL_CONFIG = dict()
        self.read_config()

    def save_config(self):
        with open(CFG_FILE_NAME, 'w+', encoding='utf-8') as f:
            json.dump(self.GLOBAL_CONFIG, f)

    def read_config(self):
        config_file_path = Path(Path.cwd() / CFG_FILE_NAME)
        if not config_file_path.exists():
            config_file_path.touch(exist_ok=True)
        try:
            with open(CFG_FILE_NAME, 'r', encoding='utf-8', errors='ignore') as f:
                self.GLOBAL_CONFIG = json.load(f)
                my_logger.debug(self.GLOBAL_CONFIG)
                for key, value in self.GLOBAL_CONFIG.items():
                    my_logger.debug(key, value)
        except Exception as e:
            my_logger.debug(e.__repr__())
            self.GLOBAL_CONFIG = dict()

    def write_config(self, cfg: dict):
        self.GLOBAL_CONFIG.update(cfg)
        self.save_config()

    def get_config(self, key: str):
        cfg = self.GLOBAL_CONFIG.get(key, None)
        my_logger.debug('get config: {}({})'.format(key, cfg))
        # if key == 'target_dir':
        #     my_logger.debug(GLOBAL_CONFIG[key])
        return cfg


def log_config():
    # my_logger = logging.getLogger('LogHelper')

    f_hdl = logging.FileHandler('EM_Debug.log')
    s_hdl = logging.StreamHandler()
    log_format = logging.Formatter('%(asctime)s %(filename)s %(funcName)s[%(lineno)d] %(message)s',
                                   datefmt='%Y-%m-%d %H:%M')
    f_hdl.setFormatter(log_format)
    s_hdl.setFormatter(log_format)
    my_logger.addHandler(f_hdl)
    my_logger.addHandler(s_hdl)


config = Config()


def get_config(key: str):
    return config.get_config(key)


def write_config(cfg: dict):
    my_logger.debug(cfg)
    config.write_config(cfg)


class CommQueue(QObject):
    my_sig = pyqtSignal(int)

    def __init__(self):
        super(CommQueue, self).__init__()


comm_sig = CommQueue()
